package com.szy.douyou_gateway.config.exception;

import com.szy.douyou_gateway.config.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author sunziyan
 * @date 2022/2/22
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获全局异常
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public ResultDTO handler(RuntimeException e) {
        log.error("运行时异常------------");
        log.error(e.getMessage());
        return ResultDTO.fail(e.getMessage());
    }

    /**
     * 如抛出未认证异常，返回异常信息
     *
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(value = ShiroException.class)
    public ResultDTO handler(ShiroException e) {
        log.error("运行时异常-----------------");
        log.error(e.getMessage());
        return ResultDTO.fail(401, e.getMessage());
    }


    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultDTO handler(MethodArgumentNotValidException e) {
        log.error("实体校验异常------------");
        //从异常信息中抽出第一个简短的异常信息
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return ResultDTO.fail(objectError.getDefaultMessage());
    }

}

